const TASKS_KEY = "todo_tasks";
const tasks = uni.getStorageSync(TASKS_KEY)

const UNDISPLY_HAS_DONE_ITEMS_TASKLIST = "todo_undisplay_done_items_tasklist";
const tasklist = uni.getStorageSync(UNDISPLY_HAS_DONE_ITEMS_TASKLIST) || []

export default {
    namespaced: true,

    state: {
        editing: false,

        task_id: null,

        tasks: tasks || [], // 数据,本地缓存
        
        undisply_has_done_items_tasklist: tasklist, // 数组存储需要隐藏已完成待办项的任务id
    },

    actions: {
        set_task_id({ state }, task_id) {
            state.task_id = task_id
        },

        update_tasks({ state }, tasks) {
            state.tasks = tasks || []
            uni.setStorageSync(TASKS_KEY, state.tasks);
        },
        
        update_task({state}, task){
            const index = state.tasks.findIndex(t=> t.id === task.id);
            if(index === -1) return;
            
            state.tasks.splice(index,1, task);
            uni.setStorageSync(TASKS_KEY, state.tasks);
        },
        
        add_task({state}, task){
            state.tasks.push(task);
            uni.setStorageSync(TASKS_KEY, state.tasks);
        },
        
        delete_task({state}, task){
            const index = state.tasks.findIndex(t=> t.id === task.id);
            if(index === -1) return;
            
            state.tasks.splice(index,1);
            uni.setStorageSync(TASKS_KEY, state.tasks);
        },
        
        add_undisply_has_done_items_tasklist({state}, task){
           const index =  state.undisply_has_done_items_tasklist.indexOf(task.id);
           if(index === -1) {
                state.undisply_has_done_items_tasklist.push(task.id);
                uni.setStorageSync(UNDISPLY_HAS_DONE_ITEMS_TASKLIST, state.undisply_has_done_items_tasklist);
            }
        },
        
        remove_undisply_has_done_items_tasklist({state}, task){
           const index =  state.undisply_has_done_items_tasklist.indexOf(task.id);
           if(index > -1) {
                state.undisply_has_done_items_tasklist.splice(index, 1);
                uni.setStorageSync(UNDISPLY_HAS_DONE_ITEMS_TASKLIST, state.undisply_has_done_items_tasklist);
            }
        },
    }
}
